import smtplib
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from celery import shared_task
from django.conf import settings
from django.db import transaction

from order.models import Order
from payments.models import Payment

# 定义购买后发送邮件的函数

"""
@params username:用户名
@params to:收件人邮箱
@params order_number:订单号
@params courses:购买的课程列表 拼接好的字符串
"""


@shared_task
def send_order_success_email(username, to, order_number, courses):
    # 创建邮箱对象
    msg = MIMEMultipart()
    msg['From'] = settings.EMAIL_FROM
    msg['To'] = to
    msg['Subject'] = f'课程购买成功'
    # 邮件正文
    body = f"""
            
                购买课程成功
                订单用户: {username}
                订单号: {order_number}
                课程: {courses}
                恭喜你，购买成功！
                
            
            """
    msg.attach(MIMEText(body, 'html'))

    # 创建邮件对象
    server = smtplib.SMTP_SSL(settings.SMTP_SERVER, settings.SMTP_PORT, timeout=30)
    # 登录邮箱
    server.login(settings.EMAIL_FROM, settings.EMAIL_PASSWORD)
    print("正在发送邮件")
    server.sock.settimeout(300)  # 设置超时时间
    server.send_message(msg)
    server.quit()  # 关闭连接
    # 发送邮件
    return f"订单号: {order_number}的邮件发送成功"  # 任务结果  存储backend  -->redis


@shared_task
def update_order_status(order_number):
    # 操作两个表
    with transaction.atomic():
        # 去订单表查询 改状态
        order_info = Order.objects.filter(order_number=order_number).first()
        if order_info:
            order_info.status = 3
            order_info.save()
        # 去支付记录表中查询 该状态
        payment_info = Payment.objects.filter(order_number=order_number).first()
        if payment_info:
            payment_info.pay_status = 3
            payment_info.save()
    # 去支付记录表中查询 改状态
    return f"订单号: {order_number}的订单状态更新成功 置为 3"  # 任务结果  存储backend  -->redis


# 再做一个定时任务的兜底 30分钟内没有支付 修改订单状态为3
# 1. 查询 30分钟内没有支付的订单
# 2. 修改订单状态为3
# 3. 修改支付记录表中的支付状态为3
# 4. 去配置定时任务
@shared_task
def order_timeout():
    # 1. 获取30分钟内没有支付的订单
    # order_list =
    # Order.objects.filter(status=0, create_time__lt=datetime.datetime.now() - datetime.timedelta(minutes=30))
    order_list = Order.objects.filter(status=0)
    if not order_list:
        return
    ids = []
    for i in order_list:
        ids.append(i.order_number)
    print(ids)
    with transaction.atomic():
        # 如果有 先改订单
        update_num = order_list.filter(status=0).update(status=3)
        # 再改支付记录
        payment_num = Payment.objects.filter(order_number__in=ids).update(pay_status=3, pay_remark="订单支付超时")
    return f"订单支付超时修改成功，订单数量为：{update_num}，支付记录数量为：{payment_num}"